package com.urbanski.clipboard.client.action;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.client.util.ClientUtils;

public abstract class ClientActionHandler
{
	private static final Logger LOGGER = Logger.getLogger(ClientActionHandler.class);
	
	protected ClientCommand command;
	protected String[] tokens;
	
	public ClientActionHandler(ClientCommand command, String[] tokens)
	{
		this.command = command;
		this.tokens = tokens;
	}
	
	public final void printHelp()
	{
		ClientUtils.printHelp(command);
	}
	
	public final boolean processHelpCommand(String[] tokens)
	{
		if (tokens.length > 1 && (tokens[1].equals("help") || tokens[1].equals("-help") || tokens[1].equals("-h")))
		{
			printHelp();
			return true;
		}
		else
		{
			return false;
		}
	}

	public abstract void execute() throws IOException;
	
	public static ClientActionHandler getActionHandler(ClientCommand command, String[] tokens) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
	{
		LOGGER.trace("Entering ActionHandler.getActionHandler");
		
		Class<? extends ClientActionHandler> handlerClass = command.getActionHandler();
		LOGGER.debug("Action handler for command " + command + ": " + handlerClass.toString());
		
		Constructor<? extends ClientActionHandler> constructor = handlerClass.getConstructor(String[].class);
		ClientActionHandler handler = constructor.newInstance((Object)tokens); //varargs method newInstance must interpret as a single object
		
		LOGGER.trace("Exiting ActionHandler.getActionHandler");
		return handler;
	}
}
